package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * @author hljstart
 * @create 2022-06-04-13:19
 */
@Controller
@RequestMapping("/houseImage")
public class HouseImageController {

    @Reference
    private HouseImageService houseImageService;
    //去上传图片的页面
    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String goUploadPage(@PathVariable("houseId")Long houseId, @PathVariable("type")Integer type, Map map){
        map.put("houseId",houseId);
        map.put("type",type);
        return "house/upload";
    }

    //上传房源或房产图片
    @ResponseBody
    @RequestMapping("/upload/{houseId}/{type}")
    public Result upload(Map map,@PathVariable("houseId")Long houseId,@PathVariable("type")Integer type,
                        @RequestParam("file") MultipartFile[] files){
        //判断
        try {
            if(files!=null && files.length>0){
                for (MultipartFile file : files) {
                    byte[] bytes = file.getBytes();
                    //获取图片的名字
                    String originalFilename = file.getOriginalFilename();
                    //通过UUID随机生成一个字符串上传到七牛云的图片的名字
                    String newFileName = UUID.randomUUID().toString();
                    //通过QiuniuUtil工具类长传图片到七牛云
                    QiniuUtils.upload2Qiniu(bytes,newFileName);
                    //创建HouseImage对象
                    HouseImage houseImage = new HouseImage();
                    houseImage.setHouseId(houseId);
                    houseImage.setImageName(originalFilename);
                    houseImage.setType(type);
                    //域名http://rcxr7c1gi.hn-bkt.clouddn.com/Ft8maN82z8sc0RM5FXkOYTiSoJxx
                    houseImage.setImageUrl("http://rcxr7c1gi.hn-bkt.clouddn.com/"+newFileName);
                    //调用HouseImageService中保存的方法
                    houseImageService.insert(houseImage);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok();
    }

    //删除房源或房产图片
    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable("houseId")Long houseId,@PathVariable("id")Long id){
        //根据id删除房源或者房产图片
        houseImageService.delete(id);
        return "redirect:/house/"+houseId;
    }

}
